package com.ly.emp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ly.common.core.bean.R;
import com.ly.common.core.bean.dto.CommonBatchUpdateDTO;
import com.ly.emp.constant.EmpErrorConstants;
import com.ly.emp.entity.EpmBaseRel;
import com.ly.emp.entity.HubTeamResultQuota;
import com.ly.emp.mapper.HubTeamResultQuotaMapper;
import com.ly.emp.service.DynamicTableService;
import com.ly.emp.service.IEmpCommonService;
import com.ly.emp.service.IHubTeamQuotaOrgService;
import com.ly.emp.service.IHubTeamResultQuotaService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import static java.util.stream.Collectors.groupingBy;

/**
 * 考核结果-基础定额-impl
 *
 * @author luoyun
 * @Date: 2025-05-20
 */
@Service
@RequiredArgsConstructor
public class HubTeamResultQuotaServiceImpl extends ServiceImpl<HubTeamResultQuotaMapper, HubTeamResultQuota> implements IHubTeamResultQuotaService {

    private final IEmpCommonService teamCommonService;
    private final DynamicTableService dynamicTableService;
    private final IHubTeamQuotaOrgService hubTeamQuotaOrgService;

    @Override
    public R getId(String id) {
        HubTeamResultQuota entity = this.getById(id);
        if (entity == null) {
            return R.fail("未找到对应数据");
        }
        return R.ok(entity);
    }

    @Override
    public R getList(HubTeamResultQuota entity) {
        String orgCode = entity.getOrgCode();
        if(StrUtil.isBlank(orgCode)){
            return R.fail(EmpErrorConstants.NO_TEAM);
        }
        List<String> isIntensificationList = teamCommonService.getIsIntensificationListByOrgCode(orgCode);
        List<HubTeamResultQuota> list = this.list(
                new LambdaQueryWrapper<HubTeamResultQuota>()
                        .in(HubTeamResultQuota::getOrgCode,isIntensificationList)
                        .eq(StrUtil.isNotBlank(entity.getPeriodCode()),HubTeamResultQuota::getPeriodCode,entity.getPeriodCode())
                        .eq(StrUtil.isNotBlank(entity.getSuitUnit()),HubTeamResultQuota::getSuitUnit,entity.getSuitUnit())
                        .likeRight(StrUtil.isNotBlank(entity.getFinalScoreStatus()),HubTeamResultQuota::getFinalScore, entity.getFinalScoreStatus())
                        .orderByDesc(HubTeamResultQuota::getSysCreateDate)
        );
        return R.ok(list);
    }

    @Override
    public R getPage(HubTeamResultQuota entity, Page<HubTeamResultQuota> page) {
        String orgCode = entity.getOrgCode();
        if(StrUtil.isBlank(orgCode)){
            return R.fail(EmpErrorConstants.NO_TEAM);
        }
        List<String> isIntensificationList = teamCommonService.getIsIntensificationListByOrgCode(orgCode);
        IPage<HubTeamResultQuota> pageList = this.page(page,
                new LambdaQueryWrapper<HubTeamResultQuota>()
                        .in(HubTeamResultQuota::getOrgCode,isIntensificationList)
                        .eq(StrUtil.isNotBlank(entity.getPeriodCode()),HubTeamResultQuota::getPeriodCode,entity.getPeriodCode())
                        .like(StrUtil.isNotBlank(entity.getPsnName()),HubTeamResultQuota::getPsnName,entity.getPsnName())
                        .orderByDesc(HubTeamResultQuota::getSysCreateDate)
        );
        return R.ok(pageList);
    }

    @Override
    public R add(HubTeamResultQuota entity) {
        boolean flag = this.save(entity);
        return flag ? R.ok(true, "创建成功") : R.fail("创建失败");
    }

    @Override
    public R edit(HubTeamResultQuota entity) {
        boolean flag = this.updateById(entity);
        return flag ? R.ok(true, "修改成功") : R.fail("修改失败");
    }

    @Override
    public R delete(String id) {
        boolean flag = this.removeById(id);
        return flag ? R.ok(true, "删除成功") : R.fail("删除失败");
    }

    @Override
    public R deleteBatch(String ids) {
        boolean flag = this.removeByIds(Arrays.asList(ids.split(",")));
        return flag ? R.ok(true, "批量删除成功") : R.fail("批量删除失败");
    }

    @Override
    public R updateBatch(CommonBatchUpdateDTO<HubTeamResultQuota> dto) {
        List<HubTeamResultQuota> datas = dto.getDatas();
        boolean flag = this.saveOrUpdateBatch(datas);
        return flag ? R.ok(true, "批量修改成功") : R.fail("批量修改失败");
    }

    @Override
    public R init(HubTeamResultQuota entity) {
        String orgCode = entity.getOrgCode();
        String periodCode = entity.getPeriodCode();
        if(StrUtil.isBlank(orgCode)){
            return R.fail(EmpErrorConstants.NO_TEAM);
        }
        if(StrUtil.isBlank(periodCode)){
            return R.fail(EmpErrorConstants.NO_PERIOD);
        }
        //查询当前班组全部的人员
        List<EpmBaseRel> baseRelList = teamCommonService.getBaseRelListByOrgCode(null, orgCode);
        if(CollUtil.isEmpty(baseRelList)){
            return R.fail(EmpErrorConstants.NO_REL_DATA);
        }
        R r = this.getList(entity);
        List<HubTeamResultQuota> data = (List<HubTeamResultQuota>) r.getResult();
        //已经维护的数据
        Map<String, List<HubTeamResultQuota>> hasMap =
                CollUtil.isNotEmpty(data) ? data.stream().collect(groupingBy(HubTeamResultQuota::getPsnNum)) : new HashMap<>();

        List<HubTeamResultQuota> datas = new ArrayList<>();
        baseRelList.stream().forEach(n -> {
            //不存在，则重新初始化
            if(!hasMap.containsKey(n.getPsnNum())){
                HubTeamResultQuota hubTeamResultQuota = BeanUtil.copyProperties(n,HubTeamResultQuota.class,new String[]{"seqKey"});
                hubTeamResultQuota.setPeriodCode(entity.getPeriodCode());
                hubTeamResultQuota.setStatus(100);
                datas.add(hubTeamResultQuota);
            }
        });
        boolean b = this.saveOrUpdateBatch(datas);
        return R.ok(true,"初始化成功");
    }
}
